import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { deleteDomain, getDomainList, saveDomain } from "@/api/system";
import { usePublicHooks } from "@/utils/hooks";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h, toRaw } from "vue";
import type { FormItemProps } from "../utils/types";
import { deviceDetection } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import { toBackendPageObj, toFrontendPageObj } from "@/api/utils";

export function useDomain() {
  const form = reactive({
    name: "",
    code: "",
    status: ""
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 15, 20],
    background: true,
    small: false
  });

  const columns: TableColumnList = [
    {
      label: "业务域名称",
      prop: "name",
      width: 180,
      align: "left"
    },
    {
      label: "编码",
      prop: "code",
      minWidth: 70
    },
    {
      label: "排序",
      prop: "sort",
      minWidth: 70
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status === "NORMAL" ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      minWidth: 200,
      prop: "createTime",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "描述",
      prop: "description",
      minWidth: 320
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const data = await getDomainList({
      ...toRaw(form),
      ...toBackendPageObj(pagination)
    });
    dataList.value = data.records;
    toFrontendPageObj(data, pagination);

    setTimeout(() => {
      loading.value = false;
    }, 300);
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}业务域`,
      props: {
        formInline: {
          id: row?.id ?? "",
          name: row?.name ?? "",
          code: row?.code ?? "",
          sort: row?.sort ?? 0,
          status: row?.status ?? 1,
          description: row?.description ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function save() {
          saveDomain(curData)
            .then(() => {
              message(`您${title}了业务域名称为${curData.name}的这条数据`, {
                type: "success"
              });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            })
            .catch(error => {
              console.log("error", error);
              message(error.message, {
                type: "error"
              });
            });
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              save();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              save();
            }
          }
        });
      }
    });
  }

  function handleDelete(row) {
    deleteDomain(row.id).then(() => {
      message(`您删除了业务域名称为${row.name}的这条数据`, { type: "success" });
      onSearch();
    });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改业务域 */
    openDialog,
    /** 删除业务域 */
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
